import {loginWechatCode,loginWXStatus,mainUrl} from './globalVariables'
const queryString = require('query-string');
//应用授权作用域，snsapi_base （不弹出授权页面，直接跳转，只能获取用户openid），
// snsapi_userinfo （弹出授权页面，可通过openid拿到昵称、性别、所在地。并且，
// 即使在未关注的情况下，只要用户授权，也能获取其信息）
const SCOPES = ['snsapi_base', 'snsapi_userinfo'];


class WechatAuth {

    install(Vue, options) {
        let wechatAuth = this;
        this.setAppId(options.appid);
        Vue.mixin({
            created() {
                this.$wechatAuth = wechatAuth
            }
        })

    }

    constructor() {
        this.appid = null;
        this.redirect_uri = null;
        this.scope = SCOPES[0];
        this._code = null;
        this._redirect_uri = null
    }

    /**
     * 随机生成State
     * */
    static makeState() {
        return Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15)
    }

    setAppId(appid) {
        this.appid = appid
    }

    set redirect_uri(redirect_uri) {
        this._redirect_uri = encodeURIComponent(redirect_uri)
    }

    get redirect_uri() {
        return this._redirect_uri
    }

    get state() {
        return localStorage.getItem("wechat_auth:state")
    }

    set state(state) {
        localStorage.setItem("wechat_auth:state", state)
    }

    get authUrl() {
        if (this.appid === null) {
            throw "appid must not be null"
        }
        if (this.redirect_uri === null) {
            throw "redirect uri must not be null"
        }
        this.state = WechatAuth.makeState();
        return `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${this.appid}&redirect_uri=${this.redirect_uri}&response_type=code&scope=${this.scope}&state=${this.state}#wechat_redirect`;
    }

    /**
     * 微信授权登录之后返回过来的链接解析数据使用，
     * url中有state，code这些值，
     * 如：回调地址：
     * https://www.123.com/index?code=061pzI881EW84T1Do3881LUE881pzI8z&state=1k6qdagr71bu1rzo0myzzo
     * setLoginStatus是vuex中action中的方法，0：未登录，1：微信授权登录返回，2：登录成功
     * */
    returnFromWechat(redirect_uri) {
        var url = redirect_uri;
        var wxObj = this.parseQueryString(url);
        console.log("wxObj code: "+wxObj.code);
        console.log("wxObj state: "+wxObj.state);
        this._code = wxObj.code;
        this.state = wxObj.state;
        if (wxObj.code == null) {
            localStorage.setItem(loginWXStatus, 0);
        } else {
            localStorage.setItem(loginWechatCode,wechatAuth.code);
            localStorage.setItem(loginWXStatus, 2);
            window.location.href = localStorage.getItem(mainUrl);
        }
    }

    get code() {
        if (this._code === null) {
            throw "Not get the code from wechat server!"
        }
        let code = this._code;
        this._code = null;
        return code
    }

    parseQueryString(url) {
        var obj = {};
        var keyvalue = [];
        var key = "",
            value = "";
        var paraString = url.substring(url.indexOf("?") + 1, url.length).split("&");
        for (var i in paraString) {
            keyvalue = paraString[i].split("=");
            key = keyvalue[0];
            value = keyvalue[1];
            obj[key] = value;
        }
        console.log(obj);
        return obj;
    }
}

const wechatAuth = new WechatAuth();

export default wechatAuth